/*
 * Copyright (C) 2004, Velocityme Partnership
 * TimeActions.java
 *
 * Created on 12 November 2004, 10:27
 */

package com.velocityme.www.interfaces;

import com.velocityme.session.ContactableLocal;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.session.NodeLocal.SummaryTables;
import com.velocityme.www.actionforms.TimeReportActionForm;
import com.velocityme.www.dto.TimeReportDTO;
import com.velocityme.www.utility.NodeUtil;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author  Robert
 */
public class TimeActions extends DispatchAction {
    
    /** Creates a new instance of TimeActions */
    public TimeActions() {
    }
    
    public ActionForward showTimeReportSetup(ActionMapping mapping, 
                                             ActionForm form,
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        session.setAttribute("contactablePairs", NodeUtil.getAllContactablePairs(key));
        session.setAttribute("years", NodeUtil.getInstance().getYears());
        session.setAttribute("months", NodeUtil.getInstance().getMonths());
        session.setAttribute("days", NodeUtil.getInstance().getDays());
        // setup default values
        Calendar now = Calendar.getInstance();
        TimeReportActionForm timeReportAF = new TimeReportActionForm();
        timeReportAF.reset(mapping, request);
        timeReportAF.setNodeId(nodeId);
        timeReportAF.setStartYear(now.get(Calendar.YEAR));
        timeReportAF.setStartMonth(now.get(Calendar.MONTH));
        timeReportAF.setStartDay(now.get(Calendar.DATE));
        timeReportAF.setStopYear(now.get(Calendar.YEAR));
        timeReportAF.setStopMonth(now.get(Calendar.MONTH));
        timeReportAF.setStopDay(now.get(Calendar.DATE));
        session.setAttribute("timeReportActionForm", timeReportAF);
        return mapping.findForward("ACTION_SHOW_SETUP_SUCCESS");                                            
    }
    
    public ActionForward showTimeReport(ActionMapping mapping, 
                                        ActionForm form,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        TimeReportActionForm timeReportAF = (TimeReportActionForm)form;
        Long nodeId = timeReportAF.getNodeId();
        if (request.getParameter("btnSubmit").equals("OK")) {
            String nodePath = lookupNodeBean().findNode(key, nodeId).getPathName();
            Calendar startDate = Calendar.getInstance(); startDate.clear();
            Calendar stopDate = Calendar.getInstance(); stopDate.clear();
            startDate.set(timeReportAF.getStartYear(), timeReportAF.getStartMonth(), timeReportAF.getStartDay());
            stopDate.set(timeReportAF.getStopYear(), timeReportAF.getStopMonth(), timeReportAF.getStopDay(), 23, 59, 59);
            NodeLocal nodeLocal = lookupNodeBean();
            Set<SummaryTables> summaries = new HashSet<SummaryTables>();
            if (timeReportAF.getIncludeDays())
                summaries.add(SummaryTables.DAY);
            if (timeReportAF.getIncludeEntries())
                summaries.add(SummaryTables.ENTRIES);
            if (timeReportAF.getIncludeMonths())
                summaries.add(SummaryTables.MONTH);
            if (timeReportAF.getIncludeStates())
                summaries.add(SummaryTables.STATE);
            if (timeReportAF.getIncludeTasks())
                summaries.add(SummaryTables.TASK);
            if (timeReportAF.getIncludeTypes())
                summaries.add(SummaryTables.TYPE);
            if (timeReportAF.getIncludeWeeks())
                summaries.add(SummaryTables.WEEK);
            Map<String,Object> results = nodeLocal.searchTimeLogValue(key,
                    lookupNodeBean().findNode(key, nodeId),
                    timeReportAF.getContactableIds(),
                    timeReportAF.getIsRecursive(),
                    summaries,
                    startDate.getTime(),
                    stopDate.getTime());
            TimeReportDTO timeReportDTO = new TimeReportDTO(nodePath,
                                                            startDate.getTime(),
                                                            stopDate.getTime(),
                                                            new Date(),
                                                            (Collection)results.get("Entries"),
                                                            (Collection)results.get("Names"),
                                                            (Collection)results.get("Summaries"));
            session.setAttribute("timeReportDTO", timeReportDTO);
            return mapping.findForward("ACTION_OK");
        }
        // Cancel simply displays the original node again
        else {
            request.setAttribute("nodePK", nodeId);
            return mapping.findForward("ACTION_CANCEL");
        }
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ContactableLocal lookupContactableBean() {
        try {
            Context c = new InitialContext();
            return (ContactableLocal) c.lookup("java:comp/env/ContactableBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
}
